import React, { useState, useEffect, useRef } from "react";
import "./App.scss";

function App() {
  const inputRef = useRef(null);
  const [arr, setArr] = useState([]);
  const [cur, setCur] = useState(["", ""]);
  const [wordHistory, setWordHistory] = useState({});
  const [sentenceHistory, setSentenceHistory] = useState({});
  const [maxSentenceHistory, setMaxSentenceHistory] = useState({});

  useEffect(() => {
    if (localStorage) {
      // 导入词库
      const data = localStorage.getItem("data");
      if (data) {
        const obj = JSON.parse(data);
        setArr(obj.arr);
        setWordHistory(obj.wordHistory);
        setSentenceHistory(obj.sentenceHistory);
        setMaxSentenceHistory(obj.maxSentenceHistory);
      }
    }
  }, []);

  const handleClick = () => {
    if (cur[0] !== "") {
      inputRef.current.textContent = "";
      arr.push(cur[0]);
      setCur(["", ""]);
      // 处理不同种空格
      const words = cur[0].trim().replace(/\s/g, " ").split(" ");
      words.forEach((ele) => {
        // 更新单词出现频率表
        if (ele !== "") {
          if (wordHistory[ele]) {
            wordHistory[ele] = wordHistory[ele] + 1;
          } else {
            wordHistory[ele] = 1;
          }
        }
      });
      // 更新连续词表和最频繁连续词表
      words.reduce((prev, cur) => {
        if (sentenceHistory[prev] && sentenceHistory[prev][cur]) {
          sentenceHistory[prev][cur] = sentenceHistory[prev][cur] + 1;
          if (sentenceHistory[prev][cur] > maxSentenceHistory[prev][1]) {
            maxSentenceHistory[prev] = [cur, sentenceHistory[prev][cur]];
          }
        } else {
          if (sentenceHistory[prev]) {
            sentenceHistory[prev][cur] = 1;
            if (!maxSentenceHistory[prev]) {
              maxSentenceHistory[prev] = [cur, 1];
            }
          } else {
            sentenceHistory[prev] = {};
            sentenceHistory[prev][cur] = 1;
            maxSentenceHistory[prev] = [cur, 1];
          }
        }
        return cur;
      });
      // 保存词库
      const data = {};
      data.arr = arr;
      data.wordHistory = wordHistory;
      data.sentenceHistory = sentenceHistory;
      data.maxSentenceHistory = maxSentenceHistory;
      localStorage.setItem("data", JSON.stringify(data));
    }
  };

  const handleInput = (e) => {
    const str = e.target.textContent;
    const words = str.trim().replace(/\s/g, " ").split(" ");
    if (words[0] === "") {
      setCur([str, ""]); // 输入只有空格
    } else {
      const lastWord = words[words.length - 1];
      let boo = false;
      if (str[str.length - 1].trim() !== "") {
        // 输入结尾不为空格
        let maxEle;
        let maxCount = 0;
        Object.keys(wordHistory).forEach((ele) => {
          if (
            ele.length >= lastWord.length &&
            ele.slice(0, lastWord.length) === lastWord &&
            maxCount < wordHistory[ele]
          ) {
            maxEle = ele; // 选出最频繁的可补全单词
            maxCount = wordHistory[ele];
          }
        });
        if (maxCount > 0) {
          if (maxEle.length > lastWord.length) {
            // 正常补全单词
            setCur([str, maxEle.slice(lastWord.length)]);
          } else {
            // 当单词已被补全，将补全句子
            boo = true;
          }
        } else {
          // 不补全
          setCur([str, ""]);
        }
      }
      if (boo || str[str.length - 1].trim() === "") {
        if (sentenceHistory[lastWord]) {
          if (boo) {
            // 将补全句子，且最后一个字符不为空格
            setCur([str, " ".concat(maxSentenceHistory[lastWord][0])]);
          } else {
            // 将补全句子，且最后一个字符是空格
            setCur([str, maxSentenceHistory[lastWord][0]]);
          }
        } else {
          // 不补全
          setCur([str, ""]);
        }
      }
    }
  };

  const handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      // 回车 进行输入
      handleClick();
      e.preventDefault();
    } else if (e.keyCode === 9 && cur[1] !== "") {
      e.preventDefault();
      // 进行补全
      document.execCommand("insertText", false, cur[1]);
    }
  };

  return (
    <div className="App">
      <h1>请输入</h1>
      <div>
        <div
          className="Input"
          contentEditable={true}
          onKeyDown={handleKeyDown}
          onInput={handleInput}
          ref={inputRef}
        />
        <div className="Suggestion" contentEditable={false}>
          <span className="Suggestion_left">{cur[0]}</span>
          <span className="Suggestion_right">{cur[1]}</span>
        </div>
      </div>
      <button onClick={handleClick}>确认</button>
      <ul>
        输入历史
        {arr.map((element, index) => (
          <li key={index}>{element}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
